package com.d3works.apps.account.web;

import com.d3works.apps.ReportFactory;
import com.d3works.apps.account.db.AccountingReportType;
import com.d3works.apps.account.report.IReport;
import com.d3works.apps.account.service.AccountingReportTypeService;
import com.d3works.apps.report.engine.ReportSettings;
import com.d3works.auth.AuthUtils;
import com.d3works.exception.D3worksException;
import com.d3works.exception.service.HandleExceptionResponse;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import com.d3works.meta.schema.actions.ActionView;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import java.lang.invoke.MethodHandles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AccountingReportTypeController {
  private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

  public void defaultName(ActionRequest request, ActionResponse response) {
    AccountingReportType accountingReport = request.getContext().asType(AccountingReportType.class);

    try {
      Beans.get(AccountingReportTypeService.class).setDefaultName(accountingReport);
      response.setValue("name", accountingReport.getName());
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }

  @HandleExceptionResponse
  public void printReportAndRules(ActionRequest request, ActionResponse response)
      throws D3worksException {

    AccountingReportType accountingReportType =
        request.getContext().asType(AccountingReportType.class);

    String name = I18n.get("Accounting report and rules");

    String fileLink =
        ReportFactory.createReport(IReport.ACCOUNTING_REPORT_TYPE_AND_RULES, name + "-${date}")
            .addParam("AccountingReportTypeId", accountingReportType.getId())
            .addParam("Locale", ReportSettings.getPrintingLocale(null))
            .addParam("User", AuthUtils.getUser().getName())
            .generate()
            .getFileLink();

    logger.debug("Printing " + name);

    response.setView(ActionView.define(name).add("html", fileLink).map());
  }
}
